package com.example.web.service.impl;

import com.example.web.entity.Customer;
import com.example.web.mapper.CustomerMapper;
import com.example.web.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CustomerServiceImpl implements CustomerService {
    
    @Autowired
    private CustomerMapper customerMapper;
    
    @Override
    public Map<String, Object> getCustomerList(Integer page, Integer size, String status, String keyword, Long creatorId) {
        // 计算分页偏移量
        Integer offset = (page - 1) * size;
        
        // 查询客户列表
        List<Customer> customers = customerMapper.findCustomers(creatorId, status, keyword, offset, size);
        
        // 查询总数
        Long total = customerMapper.countCustomers(creatorId, status, keyword);
        
        // 构造返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("records", customers);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        result.put("pages", (total + size - 1) / size); // 总页数
        
        return result;
    }
    
    @Override
    public Customer findById(Long id) {
        if (id == null) {
            return null;
        }
        return customerMapper.findById(id);
    }
    
    @Override
    public Customer createCustomer(Customer customer) {
        if (customer == null) {
            throw new RuntimeException("客户信息不能为空");
        }
        
        // 验证必填字段
        validateCustomer(customer, false);
        
        // 验证联系方式
        validateContact(customer, null);
        
        // 插入客户
        int result = customerMapper.insert(customer);
        if (result > 0) {
            return customerMapper.findById(customer.getId());
        }
        
        throw new RuntimeException("创建客户失败");
    }
    
    @Override
    public Customer updateCustomer(Customer customer) {
        if (customer == null || customer.getId() == null) {
            throw new RuntimeException("客户信息或ID不能为空");
        }
        
        // 检查客户是否存在
        Customer existingCustomer = customerMapper.findById(customer.getId());
        if (existingCustomer == null) {
            throw new RuntimeException("客户不存在");
        }
        
        // 验证必填字段
        validateCustomer(customer, true);
        
        // 验证联系方式
        validateContact(customer, customer.getId());
        
        // 更新客户
        int result = customerMapper.update(customer);
        if (result > 0) {
            return customerMapper.findById(customer.getId());
        }
        
        throw new RuntimeException("更新客户失败");
    }
    
    @Override
    public boolean deleteCustomer(Long id) {
        if (id == null) {
            return false;
        }
        
        // 检查客户是否存在
        Customer customer = customerMapper.findById(id);
        if (customer == null) {
            return false;
        }
        
        // 执行逻辑删除
        int result = customerMapper.deleteById(id);
        return result > 0;
    }
    
    @Override
    public List<Customer> getCustomersByCreator(Long creatorId) {
        if (creatorId == null) {
            throw new RuntimeException("创建人 ID 不能为空");
        }
        return customerMapper.findByCreatorId(creatorId);
    }
    
    /**
     * 验证客户信息
     */
    private void validateCustomer(Customer customer, boolean isUpdate) {
        if (!StringUtils.hasText(customer.getName())) {
            throw new RuntimeException("客户姓名不能为空");
        }
        
        if (!StringUtils.hasText(customer.getCompanyName())) {
            throw new RuntimeException("公司名称不能为空");
        }
        
        if (!StringUtils.hasText(customer.getStatus())) {
            throw new RuntimeException("客户状态不能为空");
        }
        
        // 验证状态值是否合法
        if (!isValidStatus(customer.getStatus())) {
            throw new RuntimeException("客户状态值不合法");
        }
        
        // 验证联系方式（至少填写一项）
        if (!StringUtils.hasText(customer.getPhone()) && !StringUtils.hasText(customer.getEmail())) {
            throw new RuntimeException("联系电话或邮箱至少填写一项");
        }
        
        // 如果是新增，验证创建人
        if (!isUpdate && customer.getCreatorId() == null) {
            throw new RuntimeException("创建人不能为空");
        }
    }
    
    /**
     * 验证联系方式唯一性
     */
    private void validateContact(Customer customer, Long excludeId) {
        if (StringUtils.hasText(customer.getPhone()) || StringUtils.hasText(customer.getEmail())) {
            int count = customerMapper.checkContactExists(customer.getPhone(), customer.getEmail(), excludeId);
            if (count > 0) {
                throw new RuntimeException("联系电话或邮箱已存在");
            }
        }
    }
    
    /**
     * 验证状态值是否合法
     */
    private boolean isValidStatus(String status) {
        return "潜在客户".equals(status) || "已联系客户".equals(status) || "已流失".equals(status);
    }
}